import axios from 'axios';

// API基础URL - 使用相对路径，通过Vite代理转发
const API_BASE_URL = '/api';

// 创建axios实例
const apiClient = axios.create({
  baseURL: API_BASE_URL,
  headers: {
    'Content-Type': 'application/json',
  },
});

// 请求拦截器 - 添加token
apiClient.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器 - 处理错误
apiClient.interceptors.response.use(
  (response) => response.data,
  (error) => {
    // 游客模式，不需要重定向到登录页面
    return Promise.reject(error);
  }
);

// ============ 用户认证 API ============
export const authAPI = {
  // 注册
  register: (data) => apiClient.post('/auth/register', data),
  // 登录
  login: (data) => apiClient.post('/auth/login', data),
  // 获取当前用户信息
  getCurrentUser: () => apiClient.get('/auth/me'),
};

// ============ 题目管理 API ============
export const exerciseAPI = {
  // 获取题目列表
  getExercises: (params) => apiClient.get('/exercises', { params }),
  // 获取单个题目
  getExercise: (id) => apiClient.get(`/exercises/${id}`),
  // 获取随机题目
  getRandomExercise: (params) => apiClient.get('/exercises/random/one', { params }),
};

// ============ 提交管理 API ============
export const submissionAPI = {
  // 提交写作
  createSubmission: (data) => apiClient.post('/submissions', data),
  // 获取提交详情
  getSubmission: (id) => apiClient.get(`/submissions/${id}`),
  // 获取提交历史
  getSubmissions: (params) => apiClient.get('/submissions', { params }),
  // 获取统计信息
  getStatistics: () => apiClient.get('/submissions/stats/overview'),
};

// ============ 用户管理 API ============
export const userAPI = {
  // 获取用户统计
  getUserStats: () => apiClient.get('/users/stats/overview'),
};

export default apiClient;

